<template>
	<div :class="['widgets-home', customizing ? 'customizing' : '']" ref="main">
		<div class="widgets-content">
			<el-form :model="form" :rules="rules" ref="dialogForm" :disabled="mode == 'show'" label-width="110px" label-position="top">
				<el-row :gutter="1">
					<el-col :span="24">
                        <div class="titleBox">
                            {{mode=='show'?'查看BOM单':mode == 'edit'?'编辑BOM单':'新增BOM单'}}
                            <div>
                                <el-button type="primary" @click="submit" :disabled="mode == 'show'">保存</el-button>
                                <el-button type="primary" @click="submit" :disabled="mode == 'show'">保存并新增</el-button>
                                <el-button type="primary" @click="submit" :disabled="mode == 'show'">审核</el-button>
                                <el-button type="danger" @click="submit" :disabled="mode == 'show'">退出</el-button>
                            </div>
                        </div>
					</el-col>
				</el-row>
				<el-card class="box-card">
					<el-row :gutter="1">
						<el-col :span="24">
							<div class="titleBox titleBox1">
								基本信息
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="1">
						<el-col :xs="24" :sm="3">
							<el-form-item label="BOM单编号" prop="bom_code">
								<el-input v-model="form.bom_code" placeholder="请输入(不填写自动生成)" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="BOM分类" prop="bom_cate_id">
                                <el-select v-model="form.bom_cate_id" placeholder="请选择分类" style="width:100%" clearable filterable>
                                    <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"/>
                                </el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="版本" prop="fver">
								<el-input v-model="form.fver" placeholder="请输入" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
				<el-card class="box-card">
					<el-row :gutter="1">
						<el-col :span="24">
							<div class="titleBox titleBox1">
								产品信息
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="1">
						<el-col :xs="24" :sm="3">
							<el-form-item label="物料编码">
								<el-input v-model="materCode" placeholder="请输入" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="物料名称">
								<div class="selectBox">
									<el-input v-model="materName" placeholder="请选择" readonly class="input" @click="selectCp"></el-input>
								</div>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="规格型号">
								<el-input v-model="materSpec" placeholder="请输入" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="基本单位">
								<el-input v-model="materUnit" placeholder="请输入" readonly></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="成品率（%）" prop="rate">
								<el-input v-model="form.rate" placeholder="请输入" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="3">
							<el-form-item label="产品产量" prop="all_number">
								<el-input v-model="form.all_number" placeholder="请输入" clearable></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-card>
				<el-card class="box-card">
					<el-row :gutter="1">
						<el-col :span="24">
							<div class="titleBox titleBox1">
								子件信息
							</div>
						</el-col>
					</el-row>
					<el-row :gutter="1">
						<el-col :span="24">
                            <el-button type="primary" size="small" @click="selectChild" :disabled="mode == 'show'">选择物料</el-button>
							<sc-form-table ref="table" v-model="form.bom_child" :addTemplate="addTemplate" placeholder="暂无数据" height="260">
								<el-table-column label="物料图片" width="80" align="center">
									<template #default="scope">
										<el-image
											v-if="scope.row.goods_image && scope.row.goods_image!=''"
											style="width: 50px; height: 50px; border-radius: 5px;"
											:src="scope.row.goods_image[0]"
											:preview-src-list="scope.row.goods_image"
											preview-teleported="true"
                                            hide-on-click-modal
										></el-image>
									</template>
								</el-table-column>
								<el-table-column prop="goods_code" label="物料编码" width="200" align="center"></el-table-column>
								<el-table-column prop="goods_name" label="物料名称" align="center">
									<template #default="scope">
										<div class="selectBox">
											<el-input v-model="scope.row.goods_name" placeholder="请选择" readonly class="input" @click="selectChild(scope.row,scope.$index)"></el-input>
										</div>
									</template>
								</el-table-column>
								<el-table-column prop="goods_spec" label="规格型号" align="center"></el-table-column>
								<el-table-column prop="unit_name" label="基本单位" align="center" width="80"></el-table-column>
								<el-table-column prop="ware" label="发料仓库" align="center">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.ware" filterable style="width: 97%" placeholder="请选择">
                                            <el-option v-for="item in wareList" :key="item.id" :label="item.ware_name" :value="item.id" />
                                        </el-select>
									</template>
                                </el-table-column>
								<el-table-column prop="use_number" label="材料用量" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.use_number" placeholder="请输入" clearable  class="input"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="loss" label="固定损耗" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.loss" placeholder="请输入" clearable  class="input"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="loss_rate" label="损耗率（%）" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.loss_rate" placeholder="请输入" clearable  class="input"></el-input>
									</template>
								</el-table-column>
								<el-table-column prop="method_all" label="发料方式" align="center">
									<template #default="scope">
										<el-input v-model="scope.row.method_all" placeholder="请输入" clearable  class="input"></el-input>
									</template>
								</el-table-column>
							</sc-form-table>
						</el-col>
					</el-row>
				</el-card>
			</el-form>
		</div>
	</div>
    <spare-list v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save = false" draggable></spare-list>
</template>

<script>
    import SpareList from '@/views/device/setting/spare/spareList.vue'
    export default {
        name: '新增BOM',
        components: {SpareList},
        data() {
            return {
                dialog: {
                    save:false,
                },
                //表单数据
                form: {
                    id: null,
                    bom_code: "",
                    fver: "",
                    goods_id: "",
                    bom_cate_id: "",
                    all_number: "",
                    rate: "",
                    status: "",
                    check_status: "",
                    bom_child:[],
                },
                materCode: "",
                materName: "",
                materSpec: "",
                materUnit: "",
                //验证规则
                rules: {
                    goods_name: [{ required: true, message: '请输入物料名称' }],
                },
                mode: '',
                addTemplate:{},
                cateList:[],
                wareList:[],
            }
        },
        mounted() {
            this.getCate()
            this.getWare()
            if (this.$route.query.id) {
                this.setData()
                this.mode = this.$route.query.zhuangtai
            }
        },
        methods: {
            // 获取分类
            async getCate(){
                var res = await this.$API.bom.bomCate.list.get();
                this.cateList = res.data
            },
            // 仓库
            async getWare(){
                var res = await this.$API.all.getWare.get();
                this.wareList = res.data
            },
            //表单注入数据
            async setData() {
                var reqData = {id: this.$route.query.id}
                var res = await this.$API.bom.bom.detail.post(reqData);
                this.form.id = this.$route.query.id
                this.form.bom_code = res.data.bom_code
                this.form.bom_cate_id = res.data.bom_cate_id
                this.form.fver = res.data.fver
                this.form.goods_id = res.data.goods_id
                this.form.rate = res.data.rate
                this.form.all_number = res.data.all_number
                this.form.status = res.data.status
                this.form.check_status = res.data.check_status
                this.materCode = res.data.goods_code
                this.materName = res.data.goods_name
                this.materSpec = res.data.goods_spec
                this.materUnit = res.data.unit_name
                this.form.bom_child  = res.data.child_detail
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
                this.materCode = "",
                this.materName = "",
                this.materSpec = "",
                this.materUnit = ""
                this.form.bom_child = []
            },
            //表单提交方法
            submit() {
                let array = []
                this.form.bom_child.map(item=>{
                    array.push({
                        goods_id:item.goods_id,
                        use_number:item.use_number,
                        ware:item.ware,
                        loss:item.loss,
                        loss_rate:item.loss_rate,
                        method_all:item.method_all,
                    })
                })
                this.form.bom_child = array
                this.$refs.dialogForm.validate(async (valid) => {
                    if (valid) {
                        this.isSaveing = true;
                        var res = [];
                        if (this.form.id) {
                            res = await this.$API.bom.bom.edit.post(this.form);
                        } else {
                            res = await this.$API.bom.bom.add.post(this.form);
                        }
                        this.isSaveing = false;
                        if (res.code == 1) {
                            // this.$emit('success', this.form, this.mode)
                            // this.visible = false;
                            this.$message.success("操作成功")
                            if (this.mode == 'add') {
                                this.resetForm('dialogForm')
                            } else {
                                this.setData()
                            }
                        } else {
                            this.$alert(res.message, "提示", {type: 'error'})
                        }
                    } else {
                        return false;
                    }
                })
            },
            selectCp(){
                if(this.mode != 'show'){
                    this.dialog.save = true
                    this.$nextTick(() => {
                        this.$refs.saveDialog.open('bom')
                    })
                }
            },
            selectChild(row,index){
                this.dialog.save = true
                this.$nextTick(() => {
                    this.$refs.saveDialog.open('bomChild').setData(index)
                })
            },
            handleSuccess(data,mode,index){
                if(mode == 'bom'){
                    this.form.goods_id = data[0].id
                    this.materCode = data[0].goods_code
                    this.materName = data[0].goods_name
                    this.materSpec = data[0].goods_spec
                    this.materUnit = data[0].unit_name
                }else{
                    if(index == undefined){
                        let array = []
                        data.map((item)=>{
                            array.push({
                                goods_id:item.id,
                                goods_image:item.goods_image,
                                goods_code:item.goods_code,
                                goods_name:item.goods_name,
                                goods_spec:item.goods_spec,
                                unit_name:item.unit_name,
                                ware:item.ware_id,
                            })
                        })
                        let existingIds = this.form.bom_child.map(item => item.goods_id);
                        for(let i = array.length - 1; i >= 0; i--){
                            if(existingIds.includes(array[i].goods_id)){
                                array.splice(i, 1);
                            }
                        }
                        this.form.bom_child = [...this.form.bom_child,...array]
                    }else{
                        let existingIds = this.form.bom_child.map(item => item.goods_id);
                        if(!existingIds.includes(data[0].id)){
                            this.form.bom_child[index].goods_id = data[0].id
                            this.form.bom_child[index].image = data[0].goods_image
                            this.form.bom_child[index].goods_code = data[0].goods_code
                            this.form.bom_child[index].goods_name = data[0].goods_name
                            this.form.bom_child[index].goods_spec = data[0].goods_spec
                            this.form.bom_child[index].unit_name = data[0].unit_name
                            this.form.bom_child[index].ware = data[0].ware_id
                        }
                    }
                }
            },
        },
    }
</script>

<style>
.sc-upload-multiple[data-v-f680f9e4] .el-upload--picture-card {
	width: 60px;
	height: 60px;
}

[data-v-f680f9e4] .el-upload-list__item {
	width: 60px;
	height: 60px;
}
</style>
<style lang="scss">
.el-card__body{
    padding: 15px !important;
}
.widgets-home {
	display: flex;
	flex-direction: row;
	flex: 1;
	min-height: 100%;
	max-height: 100%;
}

.widgets-content {
	flex: 1;
	overflow: auto;
	overflow-x: hidden;
	padding: 0 15px;
	.selectBox {
		display: flex;
		align-items: center;
	}
	.el-col {
		margin-right: 20px;
	}
	.el-form-item {
		flex-direction: column;
		justify-content: flex-start;
		align-items: flex-start;
		.el-form-item__label {
			justify-content: flex-start;
		}
		.el-form-item__content {
			width: 100%;
		}
	}
	.box-card {
		margin-bottom: 10px;
	}
	.box-card1 {
		.el-form-item__label {
			justify-content: flex-start;
			height: 0;
		}
	}
	.box-card2 {
		.el-col {
			margin-right: 0;
		}
	}
	.el-form {
		//background: #ffffff;
		//padding: 20px;
		min-height: 90%;
		.titleBox {
			font-size: 18px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			color: #333333;
			padding:5px 0;
			border-bottom: 1px solid #E6E6E6;
			margin-bottom: 14px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			// .el-button {
			// 	width: 100px;
			// 	border-radius: 10px;
			// 	height: 40px;
			// }
		}
		.titleBox1 {
			font-weight: 600;
			border: none;
			font-size: 16px;
		}
	}
}

.customizing .widgets-wrapper {
	margin-right: -360px
}

.customizing .widgets-wrapper .el-col {
	padding-bottom: 15px;
}

.customizing .widgets-wrapper .draggable-box {
	border: 1px dashed var(--el-color-primary);
	padding: 15px;
}

.customizing .widgets-wrapper .no-widgets {
	display: none;
}

.customizing .widgets-item {
	position: relative;
	margin-bottom: 15px;
}

@media (max-width: 992px) {
	.customizing .widgets {
		transform: scale(1) !important;
	}

	.customizing .widgets-aside {
		width: 100%;
		position: absolute;
		top: 50%;
		right: 0;
		bottom: 0;
	}

	.customizing .widgets-wrapper {
		margin-right: 0;
	}
}
</style>
